﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Model;
using VAdvantage.Logging;
using VAdvantage.Utility;
using SLControls.Controls;
using System.Data;
using VAdvantage.DataBase;
using System.Threading;

namespace VAdvantage.Apps.AForms
{
    public partial class VAttributeGrid : UserControl, FormPanel
    {
        #region Private Variables
        //	Window No			
        private int _windowNo = 0;
        //	FormFrame			
        private FormFrame _frame;
        // Product Attributes	
        private MAttribute[] _attributes = null;
        // Setting Grid		
        private bool _setting = false;
        //	Logger	
        private static VLogger log = VLogger.GetVLogger(typeof(VAttributeGrid).FullName);
        //	Modes	
        private static String[] MODES =
            new String[] { Msg.GetMsg(Envs.GetContext(), "ModeView") };
        private const int MODE_VIEW = 0;
        private const int MODE_PO = 0;
        private const int MODE_PRICE = 0;
        // Price List Version	
        private int _M_PriceList_Version_ID = 0;
        //private DecimalFormat _price = DisplayType.GetNumberFormat(DisplayType.CostPrice);
        // Warehouse		
        private int _M_Warehouse_ID = 0;
        //private DecimalFormat _qty = DisplayType.GetNumberFormat(DisplayType.Quantity);
        //UI
        private VComboBox vcmbA1 = null;
        private VComboBox vcmbA2 = null;
        private VComboBox vcmbPrice = new VComboBox();
        private VComboBox vcmbWH = new VComboBox();
        private VComboBox vcmbMode = new VComboBox();// CComboBox(MODES);

        #endregion

        public VAttributeGrid()
        {
            InitializeComponent();
            for (int i = 0; i < MODES.Length; i++)
            {
                vcmbMode.Items.Add(MODES[i]);
            }
        }
        public void Init(int WindowNo, FormFrame frame)
        {
            SetBusy(true);
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                _attributes = MAttribute.GetOfClient(Envs.GetContext(), true, true);
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => fillCombo());
            });
            _windowNo = WindowNo;
            _frame = frame;
            Envs.GetCtx().SetIsSOTrx(_windowNo, true);
            //GetLookUp();
            this.Visibility = System.Windows.Visibility.Visible;
            _frame.ContentGrid.Children.Add(this);
            LayoutRoot.Background = new SolidColorBrush(DataBase.GlobalVariable.WINDOW_BACK_COLOR);
            vtabGen.Header =  Msg.GetMsg(Envs.GetContext(),"AttributeGrid");
            _frame.Width = 300;
            _frame.Height = 300;
            vtabsel.Header = Msg.GetMsg(Envs.GetContext(), "Selection");


            //
            //fillCombo();
            FillPicks();
            //LayOut();
            //	Grid

        }

        private void SetBusy(bool value)
        {

            this.IsEnabled = !value;
            busyWindow.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            txtBusy.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
        }


        public void fillCombo()
        {
            List<KeyNamePair> vector = new List<KeyNamePair>();
            vector.Add(new KeyNamePair(0, ""));
            for (int i = 0; i < _attributes.Length; i++)
            {
                vector.Add(_attributes[i].GetKeyNamePair());
            }
            vcmbA1 = new VComboBox();//CComboBox(vector);
            for (int i = 0; i < vector.Count; i++)
            {
                vcmbA1.Items.Add(vector[i]);
            }

            vcmbA2 = new VComboBox(); //CComboBox(vector);
            for (int i = 0; i < vector.Count; i++)
            {
                vcmbA2.Items.Add(vector[i]);
            }
            SetBusy(false);
            LayOut();
        }

        public void Dispose()
        {
            if (_frame != null)
            {
                _frame.Dispose();
            }
            _frame = null;
        }

        private void LayOut()
        {

            lblA1.Content = Msg.GetElement(Envs.GetContext(), "M_Attribute_ID") + " 1";
            lblA2.Content = Msg.GetElement(Envs.GetContext(), "M_Attribute_ID") + " 2";
            vlblPriceList.Content = Msg.GetElement(Envs.GetContext(), "M_PriceList_ID");
            vlblWareHouse.Content = Msg.GetElement(Envs.GetContext(), "M_Warehouse_ID");
            //vlblMode.Content = Msg.GetMsg(Envs.GetContext(), "Mode");
            // 
            // cmbA1
            // 
            //this.cmbA1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            vcmbA1.HorizontalAlignment = HorizontalAlignment.Stretch;
            //this.cmbA1.FormattingEnabled = true;
            /// this.cmbA1.Location = new System.Drawing.Point(109, 3);
            vcmbA1.Name = "cmbA1";
            ///this.cmbA1.Size = new System.Drawing.Size(242, 21);
            vcmbA1.TabIndex = 1;
            vcmbA1.Margin = new Thickness(0, 5, 5, 0);
            // 
            // cmbA2
            // 
            //this.cmbA2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            vcmbA2.HorizontalAlignment = HorizontalAlignment.Stretch;
            //this.cmbA2.FormattingEnabled = true;
            //this.cmbA2.Location = new System.Drawing.Point(109, 28);
            vcmbA2.Name = "cmbA2";
            //this.cmbA2.Size = new System.Drawing.Size(242, 21);
            vcmbA2.TabIndex = 5;
            vcmbA2.Margin = new Thickness(0, 5, 5, 0);
            // 
            // cmbPrice
            // 
            //.cmbPrice.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            vcmbPrice.HorizontalAlignment = HorizontalAlignment.Stretch;
            //this.cmbPrice.FormattingEnabled = true;
            //this.cmbPrice.Location = new System.Drawing.Point(109, 53);
            vcmbPrice.Name = "cmbPrice";
            //this.cmbPrice.Size = new System.Drawing.Size(242, 21);
            vcmbPrice.TabIndex = 6;
            vcmbPrice.Margin = new Thickness(0, 5, 5, 0);
            // 
            // cmbWH
            // 
            //this.cmbWH.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
            vcmbWH.HorizontalAlignment = HorizontalAlignment.Stretch;
            //this.cmbWH.FormattingEnabled = true;
            //this.cmbWH.Location = new System.Drawing.Point(109, 78);
            vcmbWH.Name = "cmbWH";
            //this.cmbWH.Size = new System.Drawing.Size(242, 21);
            vcmbWH.TabIndex = 7;
            vcmbWH.Margin = new Thickness(0, 5, 5, 0);

            // 
            // cmbMode
            // 
            //this.vcmbMode.Anchor = System.Windows.Forms.AnchorStyles.Left;
            vcmbMode.HorizontalAlignment = HorizontalAlignment.Left;
            //this.vcmbMode.FormattingEnabled = true;
            //this.vcmbMode.Location = new System.Drawing.Point(108, 8);
            vcmbMode.Name = "cmbMode1";
            vcmbMode.Margin = new Thickness(2);
            vcmbMode.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
            vcmbMode.Height = 20;
            vcmbMode.Width = 140;
            //this.vcmbMode.Size = new System.Drawing.Size(201, 21);
            vcmbMode.TabIndex = 4;
            vcmbMode.SelectionChanged += new SelectionChangedEventHandler(vcmbMode_SelectionChanged);
            vbtnOk.Click += new RoutedEventHandler(vbtnOk_Click);
            vbtnCancel.Click += new RoutedEventHandler(vbtnCancel_Click);
            vtabAttrib.SelectionChanged += new SelectionChangedEventHandler(vtabAttrib_SelectionChanged);

            vdgvselect.Children.Add(vcmbA1);
            Grid.SetColumn(vcmbA1, 1);
            Grid.SetRow(vcmbA1, 0);
            vdgvselect.Children.Add(this.vcmbA2);
            Grid.SetColumn(vcmbA2, 1);
            Grid.SetRow(vcmbA2, 1);
            vdgvselect.Children.Add(this.vcmbPrice);
            Grid.SetColumn(vcmbPrice, 1);
            Grid.SetRow(vcmbPrice, 2);
            vdgvselect.Children.Add(this.vcmbWH);
            Grid.SetColumn(vcmbWH, 1);
            Grid.SetRow(vcmbWH, 3);


        }

        /// <summary>
        /// Fill Picks with values
        /// </summary>
        private void FillPicks()
        {
            SetBusy(true);
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                //	Price List
                String sql = "SELECT M_PriceList_Version.M_PriceList_Version_ID,"
                    + " M_PriceList_Version.Name || ' (' || c.Iso_Code || ')' AS ValueName "
                    + "FROM M_PriceList_Version, M_PriceList pl, C_Currency c "
                    + "WHERE M_PriceList_Version.M_PriceList_ID=pl.M_PriceList_ID"
                    + " AND pl.C_Currency_ID=c.C_Currency_ID"
                    + " AND M_PriceList_Version.IsActive='Y' AND pl.IsActive='Y'";
                //	Add Access & Order
                sql = MRole.GetDefault().AddAccessSQL(sql, "M_PriceList_Version", true, false)	// fully qualidfied - RO 
                    + " ORDER BY M_PriceList_Version.Name";
                //IDataReader idr = null;
                //try
                //{

                //    idr = DB.ExecuteReader(sql, null, null);
                //    while (idr.Read())
                //    {
                //        KeyNamePair kn = new KeyNamePair(Util.GetValueOfInt(idr[0]), idr[1].ToString());
                //        
                //        vcmbPrice.Items.Add(kn);
                //    }
                IDataReader idr = DB.ExecuteReader(sql, null, null);
                DataTable dt = new DataTable();
                dt.Load(idr);
                Dispatcher.BeginInvoke(delegate
                {

                    vcmbPrice.Items.Add(new KeyNamePair(0, ""));

                    if (dt != null)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            KeyNamePair kn = new KeyNamePair(Util.GetValueOfInt(dt.Rows[i][0]), dt.Rows[i][1].ToString());
                            vcmbPrice.Items.Add(kn);
                        }
                    }
                });
                //	Warehouse
                sql = "SELECT M_Warehouse_ID, Value || ' - ' || Name AS ValueName "
                    + "FROM M_Warehouse "
                    + "WHERE IsActive='Y'";
                sql = MRole.GetDefault().AddAccessSQL(sql,
                        "M_Warehouse", MRole.SQL_NOTQUALIFIED, MRole.SQL_RO)
                    + " ORDER BY Value";

                idr = null;
                idr = DB.ExecuteReader(sql, null, null);
                dt = new DataTable();
                dt.Load(idr);
                //while (idr.Read())
                //{
                //    KeyNamePair kn = new KeyNamePair
                //        (Util.GetValueOfInt(idr["M_Warehouse_ID"]), idr["ValueName"].ToString());
                //    vcmbWH.Items.Add(kn);
                //}
                Dispatcher.BeginInvoke(delegate
                {
                    vcmbWH.Items.Add(new KeyNamePair(0, ""));
                    if (dt != null)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            KeyNamePair kn = new KeyNamePair
                                (Util.GetValueOfInt(dt.Rows[i][0]), dt.Rows[i][1].ToString());
                            vcmbWH.Items.Add(kn);
                        }
                    }
                    SetBusy(false);
                });


                if (idr != null)
                {
                    idr.Close();
                    idr = null;
                }

            });
        }

        private void GridOK()
        {
            int mode = vcmbMode.SelectedIndex;
            //	Create PO
            if (mode == MODE_PO)
            {
                CreatePO();
                vcmbMode.SelectedIndex = MODE_VIEW;
                return;
            }
            //	Update Prices
            else if (mode == MODE_PRICE)
            {
                UpdatePrices();
                vcmbMode.SelectedIndex = MODE_VIEW;
                return;
            }
            else if (mode == MODE_VIEW)
            {
                ;
            }

            _frame.Dispose();
        }

        private void CreatePO()
        {

        }
        private void UpdatePrices()
        {

        }

        bool pass = false;

        /// <summary>
        /// Create Grid
        /// </summary>
        private void CreateGrid()
        {

            //vdgvGenerate.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single;
            if (vcmbA1 == null || _setting)
            {
                SetBusy(false);
                vbtnOk.IsEnabled = true;
                return;
            }
            //	init
            int indexAttr1 = vcmbA1.SelectedIndex;
            int indexAttr2 = vcmbA2.SelectedIndex;
            if (indexAttr1 == indexAttr2)
            {
                log.Warning("Same Attribute Selected");
                vtabAttrib.SelectedIndex = 0;
                SetBusy(false);
                return;
            }
            _setting = true;
            _M_PriceList_Version_ID = 0;
            KeyNamePair pl = (KeyNamePair)vcmbPrice.SelectedItem;
            if (pl != null)
            {
                _M_PriceList_Version_ID = pl.GetKey();

            }
            _M_Warehouse_ID = 0;
            KeyNamePair wh = (KeyNamePair)vcmbWH.SelectedItem;
            if (wh != null)
            {
                _M_Warehouse_ID = wh.GetKey();
            }

            //	x dimension
            int cols = 2;

            MAttributeValue[] xValues = null;
            MAttributeValue[] yValues = null;
            MAttributeValue xValue = null;
            MAttributeValue yValue = null;
            int rows = 2;
            vdgvGenerate.Children.Clear();
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                if (indexAttr1 > 0)
                {
                    xValues = _attributes[indexAttr1 - 1].GetMAttributeValues();
                }
                if (xValues != null)
                {
                    cols = xValues.Length;
                    log.Info("X - " + _attributes[indexAttr1 - 1].GetName() + " #" + xValues.Length);
                }
                if (indexAttr2 > 0)
                {
                    yValues = _attributes[indexAttr2 - 1].GetMAttributeValues();
                }
                if (yValues != null)
                {
                    rows = yValues.Length;
                    log.Info("Y - " + _attributes[indexAttr2 - 1].GetName() + " #" + yValues.Length);
                }
                Dispatcher.BeginInvoke(delegate
                {

                    //to display static label and combobox add at least one row and two columns

                    CreateRowsColumn(rows, cols);


                    log.Info("Rows=" + rows + " - Cols=" + cols);

                    for (int row = 0; row < rows; row++)
                    {
                        //RowDefinition rowDefinition = new RowDefinition();
                        //rowDefinition.Height = GridLength.Auto;
                        //vdgvGenerate.RowDefinitions.Add(rowDefinition);
                        for (int col = 0; col < cols; col++)
                        {
                            //if (row == 1 &&col>1) 
                            //{
                            //    ColumnDefinition coldef = new ColumnDefinition();
                            //    coldef.Width = new GridLength(1, GridUnitType.Star);
                            //    vdgvGenerate.ColumnDefinitions.Add(coldef);
                            //}
                            if (xValues != null)
                            {
                                xValue = xValues[col];
                            }

                            if (yValues != null)
                            {
                                yValue = yValues[row];
                            }
                            //	//log.fine("Row=" + row + " - Col=" + col);
                            //


                            if (row == 0 && col == 0)
                            {
                                //CPanel descr = new CPanel(new GridLayout(2, 1, 0, 0));
                                //'Panel descr = new Panel();
                                Label lbl1 = new Label();
                                Label lbl2 = new Label();
                                //lbl1.AutoSize = true;
                                //lbl2.AutoSize = true;
                                if (xValues != null)
                                {
                                    lbl1.Content = _attributes[indexAttr1 - 1].GetName();
                                    lbl1.FontSize = 13;
                                    // lbl1.HorizontalAlignment = HorizontalAlignment.Right;
                                    // descr.Controls.Add(new Label(_attributes[indexAttr1 - 1].GetName()));//, Label.TRAILING));
                                    vdgvGenerate.Children.Add(lbl1);
                                    Grid.SetColumn(lbl1, col);
                                    Grid.SetRow(lbl1, 1);
                                    lbl1.HorizontalAlignment = HorizontalAlignment.Right;
                                    lbl1.VerticalAlignment = VerticalAlignment.Center;
                                    lbl1.Margin = new Thickness(5, 5, 5, 0);
                                }
                                if (yValues != null)
                                {
                                    lbl2.Content = _attributes[indexAttr2 - 1].GetName();
                                    lbl2.FontSize = 13;
                                    // descr.Controls.Add(new Label(_attributes[indexAttr2 - 1].GetName()));
                                    lbl2.HorizontalAlignment = HorizontalAlignment.Left;
                                    vdgvGenerate.Children.Add(lbl2);
                                    Grid.SetColumn(lbl2, col);
                                    Grid.SetRow(lbl2, 1);
                                    lbl2.Margin = new Thickness(5, 5, 5, 0);
                                    lbl2.VerticalAlignment = VerticalAlignment.Bottom;
                                }
                                //Grid.add(descr);
                                //SetBusy(false);
                                vbtnOk.IsEnabled = true;

                            }
                            else if (row == 0)	//	column labels
                            {
                                if (xValue != null)
                                {
                                    //Grid.add(new JLabel(xValue.getName(), JLabel.TRAILING));
                                    lblA1 = new VLabel();
                                    lblA1.Content = xValue.GetName();
                                    lblA1.FontSize = 13;
                                    //lblA1.AutoSize = true;
                                    //lblA1.VerticalAlignment = VerticalAlignment.Top;
                                   // lblA1.Foreground = new SolidColorBrush(Color.FromArgb(255, 107, 192, 245));
                                    lblA1.HorizontalAlignment = HorizontalAlignment.Center;
                                    vdgvGenerate.Children.Add(lblA1);
                                    Grid.SetColumn(lblA1, col);
                                    Grid.SetRow(lblA1, 1);
                                    lblA1.Margin = new Thickness(5, 5, 5, 0);
                                    //  lblA1.HorizontalAlignment = HorizontalAlignment.Center;
                                }
                                else
                                {
                                    //Grid.add(new JLabel());
                                    //vdgvGenerate.Children.Add(new Label());
                                }
                                //SetBusy(false);
                                vbtnOk.IsEnabled = true;
                            }
                            else if (col == 0)	//	row labels
                            {
                                if (yValue != null)
                                {
                                    //Grid.add(new JLabel(yValue.getName()));
                                    lblA1 = new VLabel();
                                    lblA1.Content = yValue.GetName();
                                    lblA1.VerticalAlignment = VerticalAlignment.Center;
                                    lblA1.FontSize = 13;
                                    //lblA1.AutoSize = true;
                                    vdgvGenerate.Children.Add(lblA1);
                                    Grid.SetColumn(lblA1, col);
                                    Grid.SetRow(lblA1, row + 1);
                                    lblA1.Margin = new Thickness(5, 5, 5, 0);
                                    lblA1.HorizontalAlignment = HorizontalAlignment.Left;
                                }
                                else
                                {
                                    //Grid.add(new JLabel());
                                    //vdgvGenerate.Children.Add(new Label());
                                }
                                // SetBusy(false);
                                vbtnOk.IsEnabled = true;
                            }
                            else
                            {
                                //Object[] createList = { xValue, yValue, col, row+1 };

                                SetGridElement(xValue, yValue, col, row + 1);
                            }

                        }
                    }

                    //
                    //tabbedPane.setSelectedIndex(1);
                    vtabAttrib.SelectedIndex = 1;
                    vtabAttrib.SelectedItem = vtabGen;
                    _setting = false;
                    //_frame.pack();
                    _frame.Height = App.Current.Host.Content.ActualHeight - Convert.ToDouble(35);
                    _frame.Width = App.Current.Host.Content.ActualWidth;
                });
            });
            //this.AutoSize = false;
        }

        private void SetGridElement(MAttributeValue xValue, MAttributeValue yValue, int col, int row)
        {
            int noProducts = 0;
            StackPanel element = new StackPanel();
            Border stackBorder = new Border();
            stackBorder.BorderThickness = new Thickness(1);
            stackBorder.BorderBrush=new SolidColorBrush(Color.FromArgb(24,0,0,0));
            stackBorder.Child = element;

            element.Background = new SolidColorBrush(Colors.White);
            element.Orientation = Orientation.Vertical;
            vdgvGenerate.Children.Add(stackBorder);
            Grid.SetColumn(stackBorder, col);
            Grid.SetRow(stackBorder, row);
            //vdgvGenerate.ShowGridLines = true;
            
            
            //vdgvGenerate.ShowGridLines = true;
            //element.Height=40;
            //element.Width= 70;

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                //StackPanel element = new StackPanel();
                //element.Height=40;
                //element.Width= 70;
                //element.HorizontalAlignment = HorizontalAlignment.Stretch;
                String sql = "SELECT * FROM M_Product WHERE IsActive='Y'";
                //	Product Attributes
                if (xValue != null)
                {
                    sql += " AND M_AttributeSetInstance_ID IN "
                        + "(SELECT M_AttributeSetInstance_ID "
                        + "FROM M_AttributeInstance "
                        + "WHERE M_Attribute_ID=" + xValue.GetM_Attribute_ID()
                        + " AND M_AttributeValue_ID=" + xValue.GetM_AttributeValue_ID() + ")";
                }
                if (yValue != null)
                {
                    sql += " AND M_AttributeSetInstance_ID IN "
                        + "(SELECT M_AttributeSetInstance_ID "
                        + "FROM M_AttributeInstance "
                        + "WHERE M_Attribute_ID=" + yValue.GetM_Attribute_ID()
                        + " AND M_AttributeValue_ID=" + yValue.GetM_AttributeValue_ID() + ")";
                }
                DataTable dt = null;
                IDataReader idr = null;



                sql = MRole.GetDefault().AddAccessSQL(sql, "M_Product",
                MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
                try
                {
                    idr = DB.ExecuteReader(sql, null, null);
                    dt = new DataTable();
                    dt.Load(idr);
                    idr.Close();
                    foreach (DataRow dr in dt.Rows)
                    {
                        MProduct product = new MProduct(Envs.GetContext(), dr, null);
                        AddProduct(element, product, col, row);
                        noProducts++;
                    }
                    pass = true;
                }
                catch (Exception e)
                {
                    if (idr != null)
                    {
                        idr.Close();
                    }
                    log.Log(Level.SEVERE, sql, e);
                }
            });



            //int mode = vcmbMode.SelectedIndex;
            ////	No Products
            //if (noProducts == 0 && mode == MODE_VIEW)
            //{
            //    //	CButton button = ConfirmPanel.createNewButton(true);
            //    //	button.addActionListener(this);
            //    //	element.add(button);
            //}
            //else	//	Additional Elements
            //{
            //    if (mode == MODE_PRICE)
            //    {
            //        //	Price Field
            //    }
            //    else if (mode == MODE_PO)
            //    {
            //        //	Qty Field
            //    }
            //}

        }

        private void CreateRowsColumn(int rows, int cols)
        {

            vdgvGenerate.Children.Clear();
            vdgvGenerate.RowDefinitions.Clear();
            vdgvGenerate.ColumnDefinitions.Clear();

            cols = cols < 2 ? 2 : cols;
            rows += 1;

            int colwidth = 1;

            for (int col = 0; col < cols; col++)
            {

                ColumnDefinition coldef = new ColumnDefinition();
                if (colwidth == 1)
                {
                    coldef.Width = new GridLength(100);
                    colwidth += 1;
                }
                else
                {
                    coldef.Width = new GridLength(1, GridUnitType.Star);
                }

                vdgvGenerate.ColumnDefinitions.Add(coldef);
            }

            for (int row = 0; row < rows; row++)
            {
                if (row == 0)
                {
                    RowDefinition rowDefinition = new RowDefinition();
                    rowDefinition.Height = new GridLength(1, GridUnitType.Auto);
                    vdgvGenerate.RowDefinitions.Add(rowDefinition);
                }
                else
                {
                    RowDefinition rowDefinition = new RowDefinition();
                    rowDefinition.Height = new GridLength(1, GridUnitType.Star);
                    vdgvGenerate.RowDefinitions.Add(rowDefinition);
                }
            }


            VLabel lbl = new VLabel();
            lbl.Content = "Mode";
            lbl.Margin = new Thickness(2);
            lbl.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            vcmbMode.Margin = new Thickness(5, 0, 5, 0);
            lbl.Margin = new Thickness(5, 0, 5, 0);


            if (cols == 2)
            {
                vdgvGenerate.Children.Add(this.vcmbMode);
                Grid.SetRow(vcmbMode, 0);
                Grid.SetColumn(vcmbMode, cols - 1);


                vdgvGenerate.Children.Add(lbl);
                Grid.SetRow(lbl, 0);
                Grid.SetColumn(lbl, cols - 2);
            }
            else
            {
                vdgvGenerate.Children.Add(this.vcmbMode);
                Grid.SetRow(vcmbMode, 0);
                Grid.SetColumn(vcmbMode, 2);


                vdgvGenerate.Children.Add(lbl);
                Grid.SetRow(lbl, 0);
                Grid.SetColumn(lbl, 1);
            }
        }

        /// <summary>
        /// Get Grid Element
        /// </summary>
        /// <param name="xValue">X value</param>
        /// <param name="yValue">Y value</param>
        /// <returns>Panel with Info</returns>
        //private Panel GetGridElement(MAttributeValue xValue, MAttributeValue yValue)
        private void SetGridElement(MAttributeValue xValue, MAttributeValue yValue)
        {
            int noProducts = 0;
            StackPanel element = new StackPanel();

            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                //StackPanel element = new StackPanel();
                //element.Height=40;
                //element.Width= 70;
                //element.HorizontalAlignment = HorizontalAlignment.Stretch;
                String sql = "SELECT * FROM M_Product WHERE IsActive='Y'";
                //	Product Attributes
                if (xValue != null)
                {
                    sql += " AND M_AttributeSetInstance_ID IN "
                        + "(SELECT M_AttributeSetInstance_ID "
                        + "FROM M_AttributeInstance "
                        + "WHERE M_Attribute_ID=" + xValue.GetM_Attribute_ID()
                        + " AND M_AttributeValue_ID=" + xValue.GetM_AttributeValue_ID() + ")";
                }
                if (yValue != null)
                {
                    sql += " AND M_AttributeSetInstance_ID IN "
                        + "(SELECT M_AttributeSetInstance_ID "
                        + "FROM M_AttributeInstance "
                        + "WHERE M_Attribute_ID=" + yValue.GetM_Attribute_ID()
                        + " AND M_AttributeValue_ID=" + yValue.GetM_AttributeValue_ID() + ")";
                }
                DataTable dt = null;
                IDataReader idr = null;



                sql = MRole.GetDefault().AddAccessSQL(sql, "M_Product",
                MRole.SQL_NOTQUALIFIED, MRole.SQL_RO);
                try
                {
                    idr = DB.ExecuteReader(sql, null, null);
                    dt = new DataTable();
                    dt.Load(idr);
                    idr.Close();
                    foreach (DataRow dr in dt.Rows)
                    {
                        MProduct product = new MProduct(Envs.GetContext(), dr, null);
                        AddProduct(element, product, 0, 0);
                        noProducts++;
                    }
                    pass = true;
                }
                catch (Exception e)
                {
                    if (idr != null)
                    {
                        idr.Close();
                    }
                    log.Log(Level.SEVERE, sql, e);
                }
            });



            int mode = vcmbMode.SelectedIndex;
            //	No Products
            if (noProducts == 0 && mode == MODE_VIEW)
            {
                //	CButton button = ConfirmPanel.createNewButton(true);
                //	button.addActionListener(this);
                //	element.add(button);
            }
            else	//	Additional Elements
            {
                if (mode == MODE_PRICE)
                {
                    //	Price Field
                }
                else if (mode == MODE_PO)
                {
                    //	Qty Field
                }
            }

        }

        /// <summary>
        /// Add Product
        /// </summary>
        /// <param name="element">panel</param>
        /// <param name="product">product</param>
        private void AddProduct(StackPanel element, MProduct product, int col, int row)
        {

            //Insets ii = new Insets(2, 4, 2, 4);
            int M_Product_ID = product.GetM_Product_ID();

            String formatted = "";

            MProductPrice pp = null;
            if (_M_PriceList_Version_ID != 0)
            {
                pp = MProductPrice.Get(Envs.GetContext(), _M_PriceList_Version_ID, M_Product_ID, null);

                if (pp != null)
                {
                    Decimal price = pp.GetPriceStd();
                    formatted = price.ToString();// _price.format(price);
                }
                else
                {
                    formatted = "-";
                }
            }


            if (_M_Warehouse_ID != 0)
            {
                Decimal qty = Util.GetValueOfDecimal(MStorage.GetQtyAvailable(_M_Warehouse_ID, M_Product_ID, 0, null));
                if (qty == null)
                {
                    formatted = "-";
                }
                else
                {
                    formatted = qty.ToString();//_qty.format(qty);
                }
            }


            Dispatcher.BeginInvoke(delegate
            {

                // StackPanel element = new StackPanel();
                //element.Height = 40;
                //element.Width = 70;
                //element.HorizontalAlignment = HorizontalAlignment.Stretch;


                Grid pe = new Grid();
                Border gridBorder = new Border();
                gridBorder.BorderThickness = new Thickness(2);
                gridBorder.BorderBrush=new SolidColorBrush(Colors.White);
                gridBorder.Child = pe;

                pe.Background = new SolidColorBrush(Colors.White);
                pe.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
                pe.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });

                pe.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
                pe.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

               // pe.ShowGridLines = true;

                Label lbl = new Label();
                lbl.Content = product.GetValue();
                lbl.VerticalAlignment = VerticalAlignment.Top;
                //lbl.AutoSize = true;
                pe.Children.Add(lbl);
                Grid.SetRow(lbl, 0);
                Grid.SetColumn(lbl, 0);
                lbl.Margin = new Thickness(2);


                lbl = new Label();
                lbl.Content = formatted.ToString();
                lbl.VerticalAlignment = VerticalAlignment.Top;
                lbl.Margin = new Thickness(2);
                pe.Children.Add(lbl);
                Grid.SetColumn(lbl, 1);
                Grid.SetRow(lbl, 0);

                lbl = new Label();
                lbl.Content = product.GetName();
                lbl.VerticalAlignment = VerticalAlignment.Top;
                lbl.Margin = new Thickness(2);
                pe.Children.Add(lbl);
                Grid.SetColumn(lbl, 0);
                Grid.SetRow(lbl, 1);
                formatted = "";


                lbl = new Label();
                lbl.VerticalAlignment = VerticalAlignment.Top;
                lbl.Content = formatted.ToString();
                lbl.Margin = new Thickness(2);
                element.Children.Add(gridBorder);

                pass = true;
                SetBusy(false);
                vbtnOk.IsEnabled = true;
            });

        }


        public static void main(String[] args)
        {
            //Vienna.startup(true);
            Envs.GetCtx().SetContext("#AD_Client_ID", 11);
            FormFrame ff = new FormFrame();
            ff.OpenForm(1111, "VFramwork.Apps.form.VAttributeGrid", "Attribute Table");
            //ff.pack();
            //AEnv.showCenterScreen(ff);
            ff.Show();
        }
        void vbtnCancel_Click(object sender, RoutedEventArgs e)
        {
            _frame.Dispose();
        }

        void vbtnOk_Click(object sender, RoutedEventArgs e)
        {
            vbtnOk.IsEnabled = false;
            SetBusy(true);
            if (vtabAttrib.SelectedIndex == 0)
            {
                CreateGrid();
            }
            else
            {
                GridOK();
                _frame.Dispose();
            }
        }

        void vcmbMode_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            SetBusy(true);
            CreateGrid();
        }

        void vtabAttrib_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (vtabAttrib.SelectedIndex == 1)
            {
                SetBusy(true);
                txtBusy.Text = Msg.GetMsg("Processing");
                CreateGrid();
            }

        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

        }


        private void busyWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }
    }
}
